# -*- coding: utf-8 -*-

from odoo import http
from odoo.http import request
from .main import api_response, validate_token, require_admin, check_activity_permission
import logging

_logger = logging.getLogger(__name__)


class RegistrationController(http.Controller):

    @http.route('/api/v1/activities/<int:activity_id>/registrations', type='http', auth='public', methods=['GET', 'POST'], csrf=False, cors='*')
    def registrations(self, activity_id, **kwargs):
        """获取报名列表 / 提交报名"""
        try:
            if request.httprequest.method == 'GET':
                # 手动验证Token（type='http'需要手动验证）
                token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
                _logger.info(f'🔍 GET /activities/{activity_id}/registrations: token={token[:20] if token else "无"}...')
                
                if not token:
                    _logger.warning('⚠️ 未提供Token')
                    return request.make_json_response(api_response(False, message='请先登录', code=401))
                
                user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
                
                if not user or not user.check_token(token):
                    _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                    return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
                
                request.wechat_user = user
                _logger.info(f'💚 Token验证成功: 用户={user.name}')
                
                # 获取报名列表
                domain = [('activity_id', '=', activity_id)]
                
                if kwargs.get('status'):
                    domain.append(('status', '=', kwargs['status']))
                
                page = int(kwargs.get('page', 1))
                page_size = int(kwargs.get('page_size', 10))
                offset = (page - 1) * page_size
                
                _logger.info(f'📋 查询报名: domain={domain}, page={page}')
                
                registrations = request.env['speech.registration'].sudo().search(
                    domain, limit=page_size, offset=offset, order='create_date desc'
                )
                
                total = request.env['speech.registration'].sudo().search_count(domain)
                
                _logger.info(f'📊 找到 {len(registrations)} 条报名，总数={total}')
                
                items = []
                for reg in registrations:
                    items.append({
                        'id': reg.id,
                        'name': reg.name,
                        'phone': reg.phone,
                        'email': reg.email,
                        'topic': reg.topic,
                        'introduction': reg.introduction,
                        'status': reg.status,
                        'feedback': reg.feedback,
                        'vote_count': reg.vote_count,
                        'created_at': reg.create_date.strftime('%Y-%m-%d %H:%M:%S') if reg.create_date else '',
                        'reviewed_at': reg.reviewed_date.strftime('%Y-%m-%d %H:%M:%S') if reg.reviewed_date else '',
                    })
                
                _logger.info(f'✅ 返回 {len(items)} 条报名数据')
                
                return request.make_json_response(api_response(True, {
                    'items': items,
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                }))
            
            elif request.httprequest.method == 'POST':
                # 手动验证Token（type='http'需要手动验证）
                token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
                _logger.info(f'🔍 POST /activities/{activity_id}/registrations: token={token[:20] if token else "无"}...')
                
                if not token:
                    _logger.warning('⚠️ 未提供Token')
                    return request.make_json_response(api_response(False, message='请先登录', code=401))
                
                user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
                
                if not user or not user.check_token(token):
                    _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                    return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
                
                request.wechat_user = user
                _logger.info(f'💚 Token验证成功: 用户={user.name}')
                
                # 提交报名
                import json
                body_data = request.httprequest.get_data(as_text=True)
                data = json.loads(body_data) if body_data else {}
                
                _logger.info(f'📝 提交报名: name={data.get("name")}, topic={data.get("topic")}')
                
                # 检查是否已报名
                existing = request.env['speech.registration'].sudo().search([
                    ('activity_id', '=', activity_id),
                    ('user_id', '=', user.id)
                ], limit=1)
                
                if existing:
                    _logger.warning('⚠️ 用户已报名')
                    return request.make_json_response(api_response(False, message='您已报名该活动'))
                
                registration = request.env['speech.registration'].sudo().create({
                    'activity_id': activity_id,
                    'user_id': user.id,
                    'name': data['name'],
                    'phone': data['phone'],
                    'email': data.get('email', ''),
                    'topic': data['topic'],
                    'introduction': data['introduction'],
                    'remark': data.get('remark', ''),
                })
                
                # 处理附件
                if data.get('attachment_urls'):
                    for url in data['attachment_urls']:
                        request.env['speech.registration.attachment'].sudo().create({
                            'registration_id': registration.id,
                            'filename': url.split('/')[-1],
                            'file_url': url,
                        })
                
                _logger.info(f'✅ 报名成功: id={registration.id}')
                
                return request.make_json_response(api_response(True, {'id': registration.id}, '报名成功'))
                
        except Exception as e:
            _logger.error(f'❌ 报名操作失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'操作失败: {str(e)}'))

    @http.route('/api/v1/registrations/<int:registration_id>', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def registration_detail(self, registration_id):
        """获取报名详情"""
        try:
            # 手动验证Token（type='http'需要手动验证）
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 GET /registrations/{registration_id}: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功: 用户={user.name}')
            
            registration = request.env['speech.registration'].sudo().browse(registration_id)
            
            if not registration.exists():
                _logger.warning(f'⚠️ 报名记录不存在: id={registration_id}')
                return request.make_json_response(api_response(False, message='报名记录不存在', code=404))
            
            attachments = []
            for att in registration.attachment_ids:
                attachments.append({
                    'filename': att.filename,
                    'url': att.file_url,
                })
            
            _logger.info(f'✅ 返回报名详情: topic={registration.topic}')
            
            return request.make_json_response(api_response(True, {
                'id': registration.id,
                'activity_name': registration.activity_id.title,
                'name': registration.name,
                'phone': registration.phone,
                'email': registration.email,
                'topic': registration.topic,
                'introduction': registration.introduction,
                'remark': registration.remark,
                'status': registration.status,
                'feedback': registration.feedback,
                'attachments': attachments,
                'created_at': registration.create_date.strftime('%Y-%m-%d %H:%M:%S') if registration.create_date else '',
            }))
            
        except Exception as e:
            _logger.error(f'❌ 获取报名详情失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'获取失败: {str(e)}'))

    @http.route('/api/v1/user/registrations', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def my_registrations(self, **kwargs):
        """获取我的报名记录"""
        try:
            # 手动验证Token（type='http'需要手动验证）
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 获取报名记录: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功，查询用户{user.name}的报名记录, user_id={user.id}')
            
            # 修改为查询新的项目报名表
            registrations = request.env['activity.item.registration'].sudo().search([
                ('user_id', '=', user.id)
            ], order='create_date desc')
            
            _logger.info(f'📊 找到 {len(registrations)} 条报名记录')
            
            # 如果没有找到，输出调试信息
            if len(registrations) == 0:
                all_regs = request.env['activity.item.registration'].sudo().search([], limit=5, order='create_date desc')
                _logger.info(f'🔍 数据库中最近的5条报名记录:')
                for reg in all_regs:
                    _logger.info(f'   - id={reg.id}, user_id={reg.user_id.id}, name={reg.name}, item={reg.item_id.name}')
            
            items = []
            for reg in registrations:
                activity = reg.item_id.activity_id
                items.append({
                    'id': reg.id,
                    'activity_id': activity.id,
                    'activity_title': activity.title,
                    'activity_start_time': activity.start_time.strftime('%Y-%m-%d %H:%M') if activity.start_time else '',
                    'activity_status': activity.status,
                    'item_id': reg.item_id.id,
                    'item_name': reg.item_id.name,
                    'name': reg.name,
                    'introduction': reg.introduction,
                    'photo_url': reg.photo_url,
                    'speech_intro': reg.speech_intro,
                    'status': reg.status,
                    'created_at': reg.create_date.strftime('%Y-%m-%d %H:%M:%S') if reg.create_date else '',
                })
            
            return request.make_json_response(api_response(True, {
                'items': items,
                'total': len(items)
            }))
            
        except Exception as e:
            _logger.error(f'获取报名记录失败: {str(e)}')
            return api_response(False, message=f'获取失败: {str(e)}')

    @http.route('/api/v1/registrations/<int:registration_id>/review', type='json', auth='public', methods=['POST'], csrf=False, cors='*')
    @validate_token
    def review_registration(self, registration_id, **kwargs):
        """审核报名（需要活动管理权限）"""
        try:
            registration = request.env['speech.registration'].sudo().browse(registration_id)
            
            if not registration.exists():
                return api_response(False, message='报名记录不存在', code=404)
            
            # 检查是否有权限审核此报名（需要是活动管理员）
            if not check_activity_permission(registration.activity_id.id):
                return api_response(False, message='您没有权限审核此报名', code=403)
            
            data = request.jsonrequest
            status = data.get('status')
            feedback = data.get('feedback', '')
            
            if status == 'approved':
                registration.action_approve()
            elif status == 'rejected':
                registration.action_reject(feedback)
            else:
                return api_response(False, message='无效的状态')
            
            return api_response(True, message='审核成功')
            
        except Exception as e:
            _logger.error(f'审核失败: {str(e)}')
            return api_response(False, message=f'审核失败: {str(e)}')

